import React, { useEffect, useState, useRef } from 'react'
import { Table, Button, Modal, Switch } from 'antd'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import UserForm from '../../../components/user-manage/UserForm';
import {getUser,addUsers,updateUsers,updateUsersState,getRegions,getRoles,deleteUsers} from "../../../api/api"

export default function UserList() {
  const [dataSource, setDataSource] = useState([]);
  const [regionsList, setregionsList] = useState([])
  const [rolesList, setrolesList] = useState([])
  const [visible, setVisible] = useState(false);
  const [visibleUpdate, setvisibleUpdate] = useState(false);
  const [userId,setuserId]=useState(0);
  const [isDisabled,setisDisabled]=useState(false)
  const {roleId,region,username}=JSON.parse(localStorage.getItem("token"))
  const addForm = useRef(null);
  const formUpdate = useRef(null)
  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      render: (region) => {
        return <b>{region === "" ? '全球' : region}</b>
      },
      filters: [...regionsList.map(item=>({
        text:item.title,
        value:item.value
      })),{
        text:"全球",
        value:"全球"
      }],
      onFilter: (value, item) => {
        if(value==="全球"){
          return item.region===""
        }
        return item.region===value
      }
    },
    {
      title: '角色名称',
      dataIndex: 'roleName'
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render: (roleState, item) => {
        return <Switch defaultChecked={roleState} onChange={(checked) => {
          //修改用户状态请求
          updateUsersState({
            id:item.id,
            roleState: Number(checked)
          })
        }} disabled={item.defaults} />
      }
    },
    {
      title: '操作',
      render: (item) => {
        return (
          <div>
            <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => confirmMethod(item)} disabled={item.defaults} />
            <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => addFormUpdateOk(item)} disabled={item.defaults} />
          </div>
        )
      }
    },
  ]
  useEffect(() => {
    const httpRequest=async ()=>{
      const roleObj={
        "1":"superadmin",
        "2":"admin",
        "3":"editor",
      }
      //获取用户信息 用户管理列表
      const res=await getUser()
      setDataSource(roleObj[roleId]==="superadmin"?res.data.data:[
        ...res.data.data.filter(item=>item.username===username),
        ...res.data.data.filter(item=>item.region===region && roleObj[item.roleId]==="editor")
      ])
    }
    httpRequest()
  }, [region,roleId,username])
  useEffect(() => {
    const httpRequest=async ()=>{
      //获取区域信息
      const res=await getRegions()
      setregionsList(res.data.data)
    }
    httpRequest()
  }, [])
  useEffect(() => {
    const httpRequest=async ()=>{
      //获取角色列表信息
      const res=await getRoles()
      setrolesList(res.data.data)
    }
    httpRequest()
  }, [])
  const confirmMethod = (item) => {
    Modal.confirm({
      title: '你确定要删除？',
      icon: <ExclamationCircleOutlined />,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        deleteMethod(item)
      }
    });
  }
  const deleteMethod = async(item) => {
    // console.log(item);
    setDataSource(dataSource.filter(data => data.id !== item.id))
    //删除用户信息
    deleteUsers({id:item.id})
  }
  const addFormOk = () => {
    // console.log('add', addForm);
    addForm.current.validateFields().then(async value => {
      // console.log(value);
      setVisible(false)
      addForm.current.resetFields();
      //添加用户信息
      const res=await addUsers({
        ...value,
        "roleState": true,
        "defaults": false
      })
      setDataSource([...dataSource, { ...res.data.data[0], role: rolesList.filter(item => item.id === value.roleId)[0] }])
    }).catch(err => {
      console.log(err);
    })
  }
  const addFormUpdateOk = (item) => {
    setvisibleUpdate(true)
    if(item.roleId===1){
      setisDisabled(true)
    }else{
      setisDisabled(false)
    }
    setuserId(item.id)
    setTimeout(() => {
      formUpdate.current.setFieldsValue(item)
    }, 0)
  }
  const formUpdateOk=()=>{
    formUpdate.current.validateFields().then(value => {
      setvisibleUpdate(false)
      formUpdate.current.resetFields();
      //修改用户信息
      updateUsers({
        id:userId,
        ...value,
      })
      setDataSource(dataSource.map(item=>{
        if(item.id===userId){
          return {
            ...item,
            ...value,
            roleName: rolesList.filter(data => data.id === value.roleId)[0].roleName
          }
        }
        return item
      }))
    }).catch(err => {
      console.log(err);
    })
  }
  return (
    <div>
      <Button type="primary" onClick={() => setVisible(true)}>添加用户</Button>
      <Table dataSource={dataSource} columns={columns} rowKey={(item) => item.id} pagination={{
        pageSize: 5,
        pageSizeOptions:[]
      }} />
      <Modal
        visible={visible}
        title="添加用户"
        okText="确认"
        cancelText="取消"
        onCancel={() => setVisible(false)}
        onOk={() => addFormOk()}
      >
        <UserForm regionsList={regionsList} rolesList={rolesList} ref={addForm}></UserForm>
      </Modal>
      <Modal
        visible={visibleUpdate}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => setvisibleUpdate(false)}
        onOk={() => formUpdateOk()}
      >
        <UserForm regionsList={regionsList} rolesList={rolesList} ref={formUpdate} isDisabled={isDisabled}></UserForm>
      </Modal>
    </div>
  )
}
